﻿#include "facade.h"
#include "ui_facade.h"

Facade::Facade(QWidget *parent) :
    TransFacade(parent),
    ui(new Ui::Facade)
{
    ui->setupUi(this);

    def_skin;

    defPos.setX(100);
    defPos.setY(100);
    this->move(defPos);

    table=TD_ITEM;
    itemEdit=nullptr;
    userLand=Location::document + APP_ROOT;
    QDir dir(userLand);
    if(!dir.exists())
        dir.mkpath(userLand);

    keyType=QMetaEnum::fromType<Qt::Key>();

    createTray(QIcon(":/ball.ico"));
    tray->setToolTip(QString::number(SP_VER) + QStringLiteral(" - 快速复制运行中"));

    createMenu();
    createLocalStorage();
    updateKeys();
}

Facade::~Facade()
{
    if(db.isOpen())
        db.close();

    delete ui;
}

void Facade::createMenu()
{
    menu=new QMenu(this);
    menu->addAction(QStringLiteral("隐藏"),this,&Facade::hide);
    menu->addAction(QStringLiteral("编辑器 (双击)"),this,&Facade::showItemEdit);
    menu->addSeparator();
    menu->addAction(QStringLiteral("退出"),QApplication::quit);
}

void Facade::showItemEdit()
{
    if(itemEdit == nullptr)
    {
        itemEdit=new ItemEdit(this,table);
        connect(itemEdit,&QDialog::accepted,this,&Facade::updateKeys);
    }

    itemEdit->move(this->x() + this->width() + 20,this->y());
    if(!itemEdit->isVisible())
        itemEdit->show();
    else
        itemEdit->hide();
}

void Facade::pop(const QString &label)
{
    tray->showMessage(label,QStringLiteral("已复制到剪贴板"));
}

void Facade::mouseDoubleClickEvent(QMouseEvent *)
{
    showItemEdit();
}

void Facade::keyPressEvent(QKeyEvent *event)
{
    if(keys.isEmpty() || items.isEmpty())
        return;

    QString keyContext{};
    if(event->modifiers() == Qt::AltModifier)
    {
        QString alt=keyType.valueToKey(Qt::Key_Alt);
        QString key=keyType.valueToKey(event->key());
        if(alt == key)
            keyContext=alt;
        else
            keyContext=alt + "+" + key;
    }
    else
        keyContext=keyType.valueToKey(event->key());

    keyContext=keyContext.remove("Key_");
    if(keys.contains(keyContext))
    {
        QString label=keys.value(keyContext);
        QString detail=items.value(label);
        if(detail.isEmpty())
            return;
        if(detail.startsWith(PRE_IMG))
        {
            QString filePath=detail.remove(PRE_IMG);
            QImage img(filePath);
            if(img.isNull())
                return;
            qApp->clipboard()->setImage(img);
        }
        else
            qApp->clipboard()->setText(detail);

        pop(label);
    }
}

void Facade::createLocalStorage()
{
    QString dbName=userLand + "QuickPaster";
    db=sp_createLocalStorage(dbName,0);

    if(!QFile::exists(dbName))
    {
        if(db.open())
        {
            QSqlQuery query;
            QString sql=QString(CREATE_TABLE).arg(table);
            if(!query.exec(sql))
            {
                QMessageBox::warning(this,QStringLiteral("异常情况"),
                                     QStringLiteral("无法创建本地数据库"));
                qDebug() << query.lastError().text();
            }
        }
        else
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("无法打开本地数据库"));
    }
}

bool Facade::db_try()
{
    if(!db.isOpen())
    {
        if(!db.open())
        {
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("无法打开数据库"));
            return false;
        }
        else
            return true;
    }
    else
        return true;
}

void Facade::updateKeys()
{
    if(!db_try())
        return;

    if(!keys.isEmpty())
        keys.clear();

    if(!items.isEmpty())
        items.clear();

    QSqlQuery query;
    QString sql=QString("select key,label,detail from %1").arg(table);
    query.exec(sql);
    while (query.next()) {
        QString key=query.value("key").toString();
        QString label=query.value("label").toString();
        QString detail=query.value("detail").toString();
        keys.insert(key,label);
        items.insert(label,detail);
    }
}
